﻿function ViewModel(options) {
    var self = this;

    //标题、数据集、弹出对话框和内容（HTML）
    self.title = ko.observable(options.title);
    self.recordSet = ko.observableArray();
    self.dialogContent = ko.observable();
    self.dialog = options.dialogId ? $("#" + options.dialogId) : $("#dialog");

    //排序
    //orderBy，defaultOrderBy & isAsc: 当前排序字段名，默认排序字段名和方向（升序/降序）
    //totalPages， pageNumbers & pageIndex：总页数，页码列表和当前页
    self.orderBy = ko.observable();
    self.isAsc = ko.observable();
    self.defaultOrderBy = options.defaultOrderBy;

    //分页
    //totalPages， pageNumbers & pageIndex：总页数，页码列表和当前页
    self.totalPages = ko.observable();
    self.pageNumbers = ko.observableArray();
    self.pageIndex = ko.observable();

    //查询条件：标签和输入值
    self.searchCriteria = ko.observableArray(options.searchCriteria);

    //作为显示数据的表格的头部：显示文字和对应的字段名（辅助排序）
    self.headers = ko.observableArray(options.headers);

    //CRUD均通过Ajax调用实现，这里提供用于获取Ajax请求地址的方法
    self.dataQueryUrlAccessor = options.dataQueryUrlAccessor;
    self.dataUpdateAccessor = options.dataUpdateAccessor;
    self.dataDeleteAccessor = options.dataDeleteAccessor;
    self.dataViewAccessor = options.dataViewAccessor;
    self.downloadExcelAccessor = options.downloadExcelAccessor;
    self.downloadExcelAdvancedAccessor = options.downloadExcelAdvancedAccessor;
    self.ApplyRequestAccessor = options.ApplyRequestAccessor;
    
    // All the filters
    self.Places = ko.observableArray();
    self.Sexs = ko.observableArray();
    self.Items = ko.observableArray();
    self.Colors = ko.observableArray();
    self.Styles = ko.observableArray();
    self.Lengths = ko.observableArray();
    self.Collars = ko.observableArray();
    self.Fronts = ko.observableArray();
    self.Sleeves = ko.observableArray();
    self.SweaterTextures = ko.observableArray();
    self.Types = ko.observableArray();
    self.selectedPlaces = ko.observableArray();
    self.selectedSexs = ko.observableArray();
    self.selectedItems = ko.observableArray();
    self.selectedColors = ko.observableArray();
    self.selectedStyles = ko.observableArray();
    self.selectedLengths = ko.observableArray();
    self.selectedCollars = ko.observableArray();
    self.selectedFronts = ko.observableArray();
    self.selectedSleeves = ko.observableArray();
    self.selectedSweaterTextures = ko.observableArray();
    self.selectedTypes = ko.observableArray();
    self.showAdvancedFilter = ko.observable(false);
    self.needDownloadPicture = ko.observable(false);
    self.showDownload = ko.observable(false);
    self.showSearching = ko.observable(false);
    self.notSearching = ko.observable(true);
    
    // All get ajax url for the filters.
    self.GetPlaceValuesAccessor = options.GetPlaceValuesAccessor;
    self.GetSexValuesAccessor = options.GetSexValuesAccessor;
    self.GetItemValuesAccessor = options.GetItemValuesAccessor;
    self.GetColorValuesAccessor = options.GetColorValuesAccessor;
    self.GetStyleValuesAccessor = options.GetStyleValuesAccessor;
    self.GetLengthValuesAccessor = options.GetLengthValuesAccessor;
    self.GetCollarValuesAccessor = options.GetCollarValuesAccessor;
    self.GetFrontValuesAccessor = options.GetFrontValuesAccessor;
    self.GetSleeveValuesAccessor = options.GetSleeveValuesAccessor;
    self.GetSweaterTextureValuesAccessor = options.GetSweaterTextureValuesAccessor;
    self.GetTypeValuesAccessor = options.GetTypeValuesAccessor;
    self.dataAdvancedQueryUrlAccessor = options.dataAdvancedQueryUrlAccessor;

    //removeData：删除操作完成后将数据从recordSet中移除
    //replaceData：修改操作后更新recordSet中相应记录
    self.removeData = options.removeData;
    self.replaceData = options.replaceData;

    // 用于下载Excel和图片的设置
    self.showProgressIcon = ko.observable(false);
    self.showResult = ko.observable(false);
    self.showErrorMessage = ko.observable(false);
    self.path = ko.observable("");
    self.errorMessage = ko.observable("");
    
    // 设置默认日期
    self.fromDate = ko.observable(new Date()).extend({ required: "" });
    self.toDate = ko.observable(new Date()).extend({ required: "" });

    function getValuesFromArray(itemArray) {
        var values = "";
        if (itemArray.length > 0) {
            for (var i = 0; i < itemArray.length; i++) {
                values += itemArray[i].ItemValue.toString() + ",";
            }
        }

        return values;
    }

    self.ChooseUrl = function() {
        var searchUrl = self.dataQueryUrlAccessor(self);
        if (self.showAdvancedFilter()) {
            searchUrl = self.dataAdvancedQueryUrlAccessor(self);
            searchUrl += self.GetFiltersParameters();
        }

        return searchUrl;
    };

    self.GetFiltersParameters = function() {
        var parameters = "";
        parameters += "Places=" + getValuesFromArray(self.selectedPlaces()) + "&";

        parameters += "Sexs=" + getValuesFromArray(self.selectedSexs()) + "&";
        parameters += "Items=" + getValuesFromArray(self.selectedItems()) + "&";
        parameters += "Colors=" + getValuesFromArray(self.selectedColors()) + "&";
        parameters += "Styles=" + getValuesFromArray(self.selectedStyles()) + "&";
        parameters += "Lengths=" + getValuesFromArray(self.selectedLengths()) + "&";
        parameters += "Collars=" + getValuesFromArray(self.selectedCollars()) + "&";
        parameters += "Fronts=" + getValuesFromArray(self.selectedFronts()) + "&";
        parameters += "Sleeves=" + getValuesFromArray(self.selectedSleeves()) + "&";
        parameters += "SweaterTextures=" + getValuesFromArray(self.selectedSweaterTextures()) + "&";
        parameters += "Types=" + getValuesFromArray(self.selectedTypes());

        return parameters;
    };

    self.appendParameters = function(parameters) {
        var url = "";
        for (var key in parameters) {
            var data = "";
            if (parameters[key] === null || parameters[key] === undefined || parameters[key] === "") {
                data = "";
            } else {
                data = parameters[key];
            }
            url += key + "=" + encodeURIComponent(data) + "&";
        }
        return url;
    };
    
    self.ChooseDownloadUrl = function () {
        var searchUrl = self.downloadExcelAccessor(self);
        var parameters = self.appendParameters({
            fromDate: self.fromDate().toLocaleDateString(),
            toDate: self.toDate().toLocaleDateString(),
            needDownloadPicture: self.needDownloadPicture()
        });
        if (self.showAdvancedFilter()) {
            searchUrl = self.downloadExcelAdvancedAccessor(self);
            parameters += self.GetFiltersParameters();
        }

        searchUrl += "?" + parameters;

        return searchUrl;
    };
    
    self.ApplyRequestUrl = function () {
        var parameters = self.appendParameters({
            fromDate: self.fromDate().toLocaleDateString(),
            toDate: self.toDate().toLocaleDateString(),
            needDownloadPicture: self.needDownloadPicture(),
            needDetailFilters: self.showAdvancedFilter()
        });
        parameters += self.GetFiltersParameters();

        return self.ApplyRequestAccessor(self) + "?" + parameters;;
    };
    
    self.downLoadExcel = function () {
        var finalUrl = self.ChooseDownloadUrl();
        self.showProgressIcon(true);
        self.showResult(false);
        self.showErrorMessage(false);
        self.showDownload(false);
        // 显示一个进度条或者处理中的icon，同时把下载按钮设置为disable.
        $.ajax(
        {
            url: finalUrl,
            type: "GET",
            success: function (result) {
                // 服务端返回url之后，不再展示icon。并把下载按钮重新展现。
                self.showProgressIcon(false);
                self.showDownload(true);
                if (result.success == true) {
                    self.showResult(true);
                    self.path(result.path);
                }
                else {
                    self.showErrorMessage(true);
                    self.errorMessage(data.error);
                }
            },
            error: function () {
                // 服务端返回url之后，不再展示icon。并把下载按钮重新展现。
                self.showProgressIcon(false);
                // 并显示对应的错误消息。
                self.showErrorMessage(true);
                self.showDownload(true);
            }
        });
    };
    
    //Search按钮
    self.search = function () {
        self.orderBy(self.defaultOrderBy);
        self.isAsc(false);
        self.pageIndex(1);
        self.showSearching(true);
        self.notSearching(false);
        
        var finalUrl = self.ChooseUrl();
        $.ajax(
        {
            url: finalUrl,
            type: "GET",
            success: function (result) {
                self.recordSet(result.Data);
                self.totalPages(result.TotalPages);
                self.resetPageNumbders();
                self.showSearching(false);
                self.notSearching(true);
                
                if (result.Data != null) {
                    if (result.Data.length > 0) {
                        self.showDownload(true);
                    }
                }
            },
            error: function () {
                self.showSearching(false);
                self.notSearching(true);
            }
        });
    };

    //Reset按钮
    self.reset = function () {
        for (var i = 0; i < self.searchCriteria().length; i++) {
            self.searchCriteria()[i].value("");
            self.search();
        }
    };

    //获取数据之后根据记录数重置页码
    self.resetPageNumbders = function () {
        self.pageNumbers.removeAll();
        for (var i = 1; i <= self.totalPages() ; i++) {
            self.pageNumbers.push(i);
        }
    };

    //点击表格头部进行排序
    self.sort = function (header) {
        if (header.canOrder == "false") {
            return;
        }
        if (self.orderBy() == header.value) {
            self.isAsc(!self.isAsc());
        }
        self.orderBy(header.value);
        self.pageIndex(1);
        var finalUrl = self.ChooseUrl();
        $.ajax(
        {
            url: finalUrl,
            type: "GET",
            success: function (result) {
                self.recordSet(result.Data);
            }
        });
    };

    //点击页码获取当前页数据
    self.turnPage = function (pageIndex) {
        self.pageIndex(pageIndex);
        
        $.ajax(
        {
            url: self.ChooseUrl(),
            type: "GET",
            success: function (result) {
                self.recordSet(result.Data);
            }
        });
    };

    //点击Update按钮弹出“修改数据”对话框
    self.onDataUpdating = function (data) {
        $.ajax(
        {
            url: self.dataUpdateAccessor(data, self),
            type: "GET",
            success: function (result) {
                self.dialogContent(result);
                self.dialog.modal("show");
            }
        });
    };

    //点击“修改数据”对话框的Save按钮关闭对话框，并修改recordSet中的数据
    self.onDataUpdated = function (data) {
        self.dialog.modal("hide");
        self.replaceData(data, self);
    };

    //点击Delete按钮删除当前记录
    self.onDataView = function (data) {
        $.ajax(
        {
            url: self.dataViewAccessor(data, self),
            type: "GET",
            success: function (result) {
                self.dialogContent(result);
                self.dialog.modal("show");
            }
        });
    };
    //点击“修改数据”对话框的Save按钮关闭对话框，并修改recordSet中的数据
    self.onDataViewed = function (data) {
        self.dialog.modal("hide");
    };
    
    //点击Delete按钮删除当前记录
    self.onDataDeleting = function (data) {
        var confirmResult = confirm("Are you sure you want to delete current record?");
        if (confirmResult != true)
            return;
        $.ajax(
        {
            url: self.dataDeleteAccessor(data, self),
            type: "GET",
            success: function (result) {
                self.removeData(result, self);
            }
        });
    };
    
    self.onDataReseted = function (data) {
        if (data.IsValid == true) {
            alert(data.ErrorMessage);
            self.dialog.modal("hide");
        } else {
            alert(data.ErrorMessage);
        }
    };
    
    // Initialize filter drop downs.
    self.getFilters = function () {
        $.ajax(
        {
            url: self.GetPlaceValuesAccessor(self),
            type: "GET",
            success: function (result) {
                self.Places(result);
                self.selectedPlaces(result);
            }
        });
        $.ajax(
        {
            url: self.GetSexValuesAccessor(self),
            type: "GET",
            success: function (result) {
                self.Sexs(result);
                self.selectedSexs(result);
            }
        });
        $.ajax(
        {
            url: self.GetItemValuesAccessor(self),
            type: "GET",
            success: function (result) {
                self.Items(result);
                self.selectedItems(result);
            }
        });
        $.ajax(
        {
            url: self.GetColorValuesAccessor(self),
            type: "GET",
            success: function (result) {
                self.Colors(result);
                self.selectedColors(result);
            }
        });
        $.ajax(
        {
            url: self.GetStyleValuesAccessor(self),
            type: "GET",
            success: function (result) {
                self.Styles(result);
                self.selectedStyles(result);
            }
        });
        $.ajax(
        {
            url: self.GetLengthValuesAccessor(self),
            type: "GET",
            success: function (result) {
                self.Lengths(result);
                self.selectedLengths(result);
            }
        });
        $.ajax(
        {
            url: self.GetCollarValuesAccessor(self),
            type: "GET",
            success: function (result) {
                self.Collars(result);
                self.selectedCollars(result);
            }
        });
        $.ajax(
        {
            url: self.GetFrontValuesAccessor(self),
            type: "GET",
            success: function (result) {
                self.Fronts(result);
                self.selectedFronts(result);
            }
        });
        $.ajax(
        {
            url: self.GetSleeveValuesAccessor(self),
            type: "GET",
            success: function (result) {
                self.Sleeves(result);
                self.selectedSleeves(result);
            }
        });
        $.ajax(
        {
            url: self.GetSweaterTextureValuesAccessor(self),
            type: "GET",
            success: function (result) {
                self.SweaterTextures(result);
                self.selectedSweaterTextures(result);
            }
        });
        $.ajax(
        {
            url: self.GetTypeValuesAccessor(self),
            type: "GET",
            success: function (result) {
                self.Types(result);
                self.selectedTypes(result);
            }
        });
    };

    self.showOrHideAdvancedFilter = function(data) {
        var isShow = data.showAdvancedFilter();
        //alert("before click, showAdvancedFilter value is :" + data.showAdvancedFilter());
        if (isShow) {
            data.showAdvancedFilter(false);
        } else {
            data.showAdvancedFilter(true);
        }
        //alert("After click, showAdvancedFilter value is :" + data.showAdvancedFilter());
    };
    
    self.getFilters();
}